﻿//15.三数之和
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;

        sort(nums.begin(), nums.end());

        int size = nums.size() - 1;

        for (int i = 0; i <= size - 2; i++)
        {
            if (nums[i] > 0)
            {
                break;
            }

            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }

            int left = i + 1, right = size;
            while (left < right)
            {
                if (nums[left] + nums[right] > -nums[i])
                {
                    right--;
                }
                else if (nums[left] + nums[right] < -nums[i])
                {
                    left++;
                }
                else
                {
                    ans.push_back({ nums[left],nums[right],nums[i] });

                    left++;
                    right--;

                    while (left < right && nums[left] == nums[left - 1])
                    {
                        left++;
                    }
                    while (right > left && nums[right] == nums[right + 1])
                    {
                        right--;
                    }

                }

            }
        }

        return ans;
    }
};